<template>
  <div>
    <h2>留言板</h2>

    <!-- 留言输入表单 -->
    <div>
      <label for="message">输入留言：</label>
      <textarea 
      id="message" 
      v-model="message"
      placeholder="请输入留言..."
      @input="calculateRemainingChars"></textarea>
      <p>剩余字符：{{ remainingChars }}</p>
      <button @click="SubmitMessage">提交留言</button>
    </div>

    <!-- 留言列表 -->
    <ul>
      <!-- 留言条目 -->
      <li v-for="(msg,index) in messages" :key="index">
        <MessageStudy @delete="removeMessage(index)">
          <!-- 自定义留言显示的插槽 -->
          <template v-slot:default>
            <span>{{ msg }}</span>
          </template>
        </MessageStudy>
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import MessageStudy from './components/MessageStudy7.vue';

const messages = ref<string[]>([]);
const message = ref('');
const remainingChars = ref(100);

const calculateRemainingChars = () => {
    remainingChars.value = 100 - message.value.length;
};
const SubmitMessage = () => {
    if (message.value.trim()){
        messages.value.push(message.value.trim());
        message.value = '';
        remainingChars.value = 100;
    }
};

const removeMessage = (index: number) => {
  messages.value.splice(index, 1);
};

</script>

<style scoped>
div {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
}

textarea {
  width: 100%;
  height: 100px;
  padding: 8px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  resize: none;
}

button {
  background-color: #28a745;
  color: white;
  padding: 10px 20px;
  border: none;
  cursor: pointer;
  border-radius: 4px;
}

button:hover {
  background-color: #218838;
}

p {
  margin-top: 0;
  font-size: 0.9em;
  color: #888;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: #f9f9f9;
}
</style>
